/* 
 * Copyright 2011 QDSS.org. All rights reserved.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.qdss.oapi4j;

import org.dom4j.Element;
import org.qdss.oapi4j.util.HttpClientFetcher;

/**
 * Api调用者
 * 
 * @author <a href="mailto:zhaofang123@gmail.com">Zhao Fangfang</a>
 * @date 2011-3-20
 * @version $Id: ApiInvoker.java 39 2011-09-27 10:41:37Z zhaofang123@gmail.com $
 */
public abstract class ApiInvoker<T> {

	protected final String appKey;
	protected final String appSecret;
	
	private final Class<?> resultGenricType;
	private HttpClientFetcher httpClientFetcher;

	/**
	 * @param appKey
	 * @param appSecret
	 */
	public ApiInvoker(String appKey, String appSecret) {
		this(appKey, appSecret, Element.class);
	}

	/**
	 * @param appKey
	 * @param appSecret
	 * @param clazz
	 */
	public ApiInvoker(String appKey, String appSecret, Class<?> clazz) {
		this.appKey = appKey;
		this.appSecret = appSecret;
		this.resultGenricType = clazz;
		this.httpClientFetcher = new HttpClientFetcher();
	}

	/**
	 * @return
	 */
	public HttpClientFetcher getHttpClientFetcher() {
		return httpClientFetcher;
	}

	/**
	 * <code>GET<code>调用
	 * 
	 * @param param
	 * @return
	 * @throws InvokeFailureException
	 */
	public Result<T> invoke(ApiParameter param) throws InvokeFailureException {
		return invokeGet(param);
	}

	/**
	 * <code>GET<code>调用
	 * 
	 * @param param
	 * @return
	 * @throws InvokeFailureException
	 */
	public Result<T> invokeGet(ApiParameter param) throws InvokeFailureException {
		return invokeMethod(param, true);
	}

	/**
	 * <code>POST<code>调用
	 * 
	 * @param param
	 * @return
	 * @throws InvokeFailureException
	 */
	public Result<T> invokePost(ApiParameter param) throws InvokeFailureException {
		return invokeMethod(param, false);
	}
	
	/**
	 * 结果集泛型类型
	 * 
	 * @return
	 */
	protected Class<?> getResultGenricType() {
		return resultGenricType;
	}

	/**
	 * 调用
	 * 
	 * @param param
	 * @param isGet
	 * @return
	 * @throws InvokeFailureException
	 */
	abstract protected Result<T> invokeMethod(ApiParameter param, boolean isGet)
			throws InvokeFailureException;
	
	/**
	 * 创建API参数
	 * 
	 * @param apiUrl
	 * @param user
	 * @param authz
	 * @return
	 */
	abstract public ApiParameter createApiParameter(String apiUrl, String user, String authz);
}
